package jobs;

import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.data.photos.UserFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import models.PicasaAlbum;
import models.PicasaPhoto;
import play.Play;
import play.cache.Cache;
import play.jobs.Job;
import siena.PersistenceManager;
import siena.PersistenceManagerFactory;

import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Cyril
 * Date: 07.08.11
 * Time: 17:07
 * To change this template use File | Settings | File Templates.
 */
public class AlbumsUpdateJob extends Job {
    private static final String albumsUrl = "https://picasaweb.google.com/data/feed/api/user/%s?kind=album";
    private static final String loadJobName = "load-job-%s";

    public AlbumsUpdateJob() {
        super();
    }

    @Override
    public void doJob() throws Exception {
        Cache.set(getLoadJobName(), true);

        List<AlbumEntry> picasaAlbums = getPicasaAlbums();
        PersistenceManager pm = PersistenceManagerFactory.getPersistenceManager(PicasaPhoto.class);
        for (AlbumEntry picasaAlbum : picasaAlbums) {
            PicasaAlbum album = PicasaAlbum.getFromEntry( picasaAlbum );
            pm.update(album);
        }

        Cache.delete(getLoadJobName());
    }

    @Override
    public void onException(Throwable e) {
        Cache.delete(getLoadJobName());
        super.onException(e);
    }

    protected List<AlbumEntry> getPicasaAlbums() throws IOException, ServiceException {
        PicasawebService myService = getService();
        URL feedUrl = new URL(String.format(albumsUrl,
                Play.configuration.getProperty("sakura.picasa.login", null)));
        UserFeed myUserFeed = myService.getFeed(feedUrl, UserFeed.class);
        List<AlbumEntry> albums = myUserFeed.getAlbumEntries();
        return albums;
    }

    protected static PicasawebService getService() throws AuthenticationException {
        PicasawebService myService = new PicasawebService( "exampleCo-exampleApp-1");
        myService.setUserCredentials(
                Play.configuration.getProperty("sakura.picasa.login"),
                Play.configuration.getProperty("sakura.picasa.pass")
        );
        return myService;
    }

    public static String getLoadJobName() {
        return String.format(loadJobName, "all");
    }

}
